package com.itljm.cxrMarket.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itljm.cxrMarket.entity.Address;
import com.itljm.cxrMarket.service.AddressService;
import com.itljm.cxrMarket.mapper.AddressMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class AddressServiceImpl extends ServiceImpl<AddressMapper, Address> implements AddressService{

    @Override
    public List<Address> getByUserId(String userId) {
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, userId)
                .orderByDesc(Address::getIsDefault)
                .orderByDesc(Address::getUpdateTime);
        return this.list(wrapper);
    }

    @Override
    @Transactional
    public boolean setDefault(Long id, String userId) {
        // 1. 先将该用户所有地址设为非默认
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Address::getIsDefault, 0)
                .eq(Address::getUserId, userId);
        this.update(updateWrapper);

        // 2. 将指定ID的地址设为默认
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.eq("user_id", userId);
        Address address = this.getOne(wrapper);
        address.setIsDefault(1);
        address.setUpdateTime(new Date());
        return this.updateById(address);
    }

    @Override
    public boolean cancelDefault(Long id, String userId) {
        QueryWrapper<Address> wrapper = new QueryWrapper<>();
        wrapper.eq("id", id);
        wrapper.eq("user_id", userId);
        Address address = this.getOne(wrapper);
        address.setIsDefault(0);
        address.setUpdateTime(new Date());
        return this.updateById(address);
    }

    @Override
    public Address getDefault(String userId) {
        return this.getOne(new LambdaQueryWrapper<Address>().eq(Address::getUserId, userId).eq(Address::getIsDefault, 1));
    }
}




